// 用户相关的仓库
import { defineStore } from 'pinia';
import { LoginData, UserInfo } from '@/api/hospital/type';
import { login } from '@/api/hospital';
import { ElMessage } from 'element-plus';
import { GET_TOKEN, SET_TOKEN, REMOCE_TOKEN } from '@/utils/user';

interface State {
	visible: boolean;
	userInfo: UserInfo;
}

const _userInfo = GET_TOKEN();

let queryStateTimer: NodeJS.Timeout;

export const useUserStore = defineStore('user', {
	state(): State {
		return {
			visible: false, // 登录组件显示/隐藏
			userInfo: (_userInfo ? _userInfo : {}) as UserInfo,
		};
	},
	actions: {
		// 用户登录
		userLogin(data: LoginData, callback?: Function) {
			login(data).then((res) => {
				if (res.code === 200) {
					this.userInfo = res.data;

					this.visible = false;

					SET_TOKEN(res.data);

					ElMessage.success('登录成功');

					callback && callback();
				} else {
					ElMessage.error(res.message);
				}
			});
		},
		// 退出登录
		logout() {
			this.userInfo = { name: '', token: '' };

			REMOCE_TOKEN();

			ElMessage.success('退出登录成功');
		},
		// 查询登录状态
		queryState(callback?: Function) {
			// 防止创建多个定时器
			clearInterval(queryStateTimer);

			// 轮询用户信息
			queryStateTimer = setInterval(() => {
				const userInfo = GET_TOKEN();

				if (userInfo) {
					this.visible = false;

					this.userInfo = userInfo;

					clearInterval(queryStateTimer);

					ElMessage.success('登录成功');

					callback && callback();
				} else if (!this.visible) {
					// 若用户一直不登陆且关闭了对话框就关闭定时器
					clearInterval(queryStateTimer);
				}
			}, 1000);
		},
	},
	getters: {},
});
